import java.io.*;
import javax.microedition.lcdui.*;

class PicIndex {
	short nImgID;
	short x;
	short y;
	short w;
	short h;
}

public class PicDrawer {
	// images array
	public static Image mImages[];

	// index
	public static PicIndex mIndex[];

	/**
	 *
	 */
	public static void LoadPics() {
		DataInputStream dis = null;
		try {
			dis = new DataInputStream(MTMMidlet.the_class.getResourceAsStream("/res/pic.ndx"));
			if (dis != null) {
				int n_png_count = dis.readInt();
				int n_pic_count = dis.readInt();
				
				mImages = new Image[n_png_count];
				mIndex = new PicIndex[n_pic_count];
				
				int n_pic_ndx = 0;
				for ( int j=0; j<n_png_count; j++ ) {
					if (j == 0) {
						mImages[j] = Resources.LoadImage("/res/p" + j);
					}

					int n_imgs = dis.readInt();
					for (int i=0; i < n_imgs; i++) {
						PicIndex ppp = mIndex[n_pic_ndx++] = new PicIndex();
						ppp.nImgID = (short)j;
						ppp.x = dis.readShort();
						ppp.y = dis.readShort();
						ppp.w = dis.readShort();
						ppp.h = dis.readShort();
					}
				}
				dis.close();
			}
		}
		catch(Exception ex) {
		}
		finally {
			dis = null;
		}
		System.gc();
	}

	/**
	 *
	 */
	public static int GetPicWidth( int n_pic_id ) {
		if ((n_pic_id >= 0) && (n_pic_id < mIndex.length)) {
			PicIndex ppp = mIndex[n_pic_id];
			return ppp.w;
		}
		return 0;
	}

	/**
	 *
	 */
	public static int GetPicHeight( int n_pic_id ) {
		if ((n_pic_id >= 0) && (n_pic_id < mIndex.length)) {
			PicIndex ppp = mIndex[n_pic_id];
			return ppp.h;
		}
		return 0;
	}

	/**
	 *
	 */
	public static void DrawPic(Graphics g, int x, int y, int w, int h, int n_pic_id, int n_anchor) {
		if ((n_pic_id >= 0) && (n_pic_id < mIndex.length)) {
			if ((n_anchor & Graphics.BOTTOM) != 0) {
				y -= mIndex[n_pic_id].h;
			}
			if ((n_anchor & Graphics.RIGHT) != 0) {
				x -= mIndex[n_pic_id].w;
			}
			if ((n_anchor & Graphics.HCENTER) != 0) {
				x -= mIndex[n_pic_id].w >> 1;
			}
			if ((n_anchor & Graphics.VCENTER) != 0) {
				y -= mIndex[n_pic_id].h >> 1;
			}
			if (MTMCanvas.setClip(g, x, y, w, h, false)) {
				g.drawImage(mImages[mIndex[n_pic_id].nImgID], x - mIndex[n_pic_id].x, y - mIndex[n_pic_id].y, Graphics.TOP | Graphics.LEFT);
			}
		}
	}

	/**
	 *
	 */
	public static void DrawPic(Graphics g, int x, int y, int n_pic_id, int n_anchor) {
		if ((n_pic_id >= 0) && (n_pic_id < mIndex.length)) {
			DrawPic(g, x, y, mIndex[n_pic_id].w, mIndex[n_pic_id].h, n_pic_id, n_anchor);
		}
	}

	/**
	 *
	 */
	public static int getTeleportNumberPicIndex(int index) {
		if (index >= 0 && index < Constants.TELEPORT_PIC_INDEX.length) {
			return Constants.TELEPORT_PIC_INDEX[index];
		}
		return PicID.nPicID_1t;
	}
}
